package com.lazydong.apiforward.server.controller;

import cn.hutool.core.io.FileUtil;
import com.lazydong.apiforward.server.constant.ServerConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.io.File;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("/update")
public class UpdateController {


    @GetMapping("/getAppNewVersion")
    public String getNewVersion() {
        String versionFile = ServerConstant.UPDATE_DIR + File.separator + ServerConstant.CLIENT_VERSION_FILE;
        if (!FileUtil.exist(versionFile)) {
            FileUtil.writeString("0.0", versionFile, StandardCharsets.UTF_8);
            return "0.0";
        }
        return FileUtil.readString(versionFile, StandardCharsets.UTF_8);
    }

    @GetMapping("/downClientUpdateExeZip")
    public Mono<ResponseEntity<Resource>> downloadClientUpdateZip() {
        return downloadFile(ServerConstant.CLIENT_EXE_UPDATE_ZIP_FILE);
    }

    @GetMapping("/downClientExeZip")
    public Mono<ResponseEntity<Resource>> downloadClientZip() {
        return downloadFile(ServerConstant.CLIENT_EXE_ZIP_FILE);
    }

    public Mono<ResponseEntity<Resource>> downloadFile(String fileName) {
        // 假设我们要下载的文件路径为 /path/to/file.txt
        log.info("download file: {}", fileName);
        String filePath = ServerConstant.UPDATE_DIR + File.separator + fileName;
        File file = new File(filePath);
        if (!file.exists()) {
            return Mono.just(ResponseEntity.notFound().build());
        }
        Resource resource = new FileSystemResource(file);
        return Mono.just(ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource));
    }
}
